<?php


namespace App\Traits;


use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;

trait BaseApplyTrait
{
    public function description()
    {
        if (is_array($this->description)) {
            $action = request()->get('action') ?: 'default';
            return collect($this->description)->get($action, '');
        }
        return $this->description;
    }

    public function index(Content $content)
    {
        $action = request()->get('action') ?: 'default';
        return $content
            ->title($this->title)
            ->description($this->description())
            ->body($this->grid($action));
    }

    public function create(Content $content)
    {
        return $content
            ->title($this->title)
            ->description(trans('admin.create'))
            ->body($this->form());
    }

    public function store()
    {
        return $this->form()->store();
    }

    public function edit($id, Content $content)
    {
        $model = $this->repository->findOrFail($id);
        $this->authorize('edit', $model);
        return $content
            ->title($this->title)
            ->description(trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    public function update($id)
    {
        $model = $this->repository->find($id);
        $this->authorize('update', $model);
        return $this->form()->update($id);
    }

    public function destroy($id)
    {
        $user = Admin::user();
        if ($user['role_type'] == 1) {
            return $this->form()->destroy($id);
        }
        $model = $this->repository->findOrFail($id);
        if (!policy_check('delete', $model)) {
            return response()->json([
                'status' => false,
                'message' => '删除失败'
            ]);
        }
        return $this->form()->destroy($id);
    }

}
